import React, { useEffect, useState } from "react"
import { connect } from "react-redux"
import instance from "../../utils/instance"
import $ from "jquery"
import "./User.css"
import { actionCreator } from "../Home/store"
import { getCookie } from "../../utils/cookie"
import Header from "../../component/Header/Header"
import QuestionCard from "../../component/QuestionCard/QuestionCard"
import AnswerCard from "../../component/AnswerCard/AnswerCard"
import EditUser from "../../template/EditUser/EditUser"

function User(props) {
    const [user, setUser] = useState(props.userInfo)
    const [liker, setLiker] = useState(0)
    const [avatar, setAvatar] = useState(props.userInfo.avatar_url)
    const [cover, setCover] = useState(props.userInfo.cover)
    const [attenQuestion, setAttenQuestion] = useState([])
    const [question, setQuestion] = useState([])
    const [likingAnswer, setLinkingAnswer] = useState([])
    const [editActive, setEditActive] = useState(false)
    const [currentContent, setCurrentContent] = useState("trends")
    useEffect(() => {
        setUser(props.userInfo)
        setAvatar(props.userInfo.avatar_url)
        setCover(props.userInfo.cover)
        if (props.userInfo._id) {
            instance.get(`users/${props.userInfo._id}/followers`)
                .then(data => {
                    let num = data.data.data.length
                    setLiker(num)
                })
        }
    }, [props.userInfo])
    useEffect(() => {
        let userId = user._id
        let token = getCookie("token")
        instance.defaults.headers.common['Authorization'] = "Bearer " + token
        if (userId) {
            instance.get(`/users/${userId}/collectingQuestions`).then(data => {
                if (data.data.errno === 0) {
                    setAttenQuestion(data.data.data)
                }
            })
            instance.get(`/users/${userId}/questions`).then(data => {
                if (data.data.errno === 0) {
                    setQuestion(data.data.data)
                }
            })
            instance.get(`/users/${userId}/likingAnswers`).then(data => {
                if (data.data.errno === 0) {
                    setLinkingAnswer(data.data.data)
                }
            })
        }
    }, [user])
    const changeUserImg = (e) => {
        $(e.target).parent().find("input").click()
    }
    const uploadImg = (e) => {
        const file = e.currentTarget.files[0]
        const form = new FormData()
        form.append("file", file)
        instance.post("/upload", form).then(data => {
            let url = data.data.data.url
            let id = user._id
            let token = getCookie("token")
            instance.defaults.headers.common['Authorization'] = "Bearer " + token
            instance.patch(`users/update/${id}`, {
                avatar_url: url
            }).then(data => {
                if (data.data.errno === 0) {
                    props.updateUserInfo(token)
                }
            })
        })
    }
    const updateCover = (e) => {
        $(e.target).parent().find("input").click()
    }
    const uploadCover = (e) => {
        const file = e.currentTarget.files[0]
        const form = new FormData()
        form.append("file", file)
        instance.post("/upload", form).then(data => {
            let url = data.data.data.url
            let id = user._id
            let token = getCookie("token")
            instance.defaults.headers.common['Authorization'] = "Bearer " + token
            instance.patch(`users/update/${id}`, {
                cover: url
            }).then(data => {
                if (data.data.errno === 0) {
                    props.updateUserInfo(token)
                }
            })
        })
    }
    const changeCurrentActive = (e) => {
        $(e.target).parent().addClass("active").siblings().removeClass("active")
    }
    return (
        <div className="user_container">
            <div className="user_header">
                <Header />
            </div>
            <div className="user_content">
                <div className="user_content_head">
                    <div className="user_cover">
                        {cover ? <img src={cover} alt="" /> : ""}
                    </div>
                    <div className="user_content_head_btn">
                        <p onClick={(e) => { updateCover(e) }}><i className="iconfont iconduomeitiicon-"></i>上传封面图片</p>
                        <input type="file" onChange={(e) => { uploadCover(e) }} />
                    </div>
                    <div className="user_content_head_info">
                        <div className="user_avatar">
                            <img src={
                                avatar === "" ? [require("../../assets/img/default_user.jpg")] : avatar
                            } alt="" />
                            <div className="changeAvatar">
                                <p onClick={(e) => { changeUserImg(e) }}>更新我的头像</p>
                                <input type="file" name="file" accept="image/*" onChange={(e) => { uploadImg(e) }} />
                            </div>
                        </div>
                        <div className="user_detail">
                            <div className="user_name">
                                <h3>{user.username}</h3>
                                <a href="#/user"><i className="iconfont iconxiajiantou"></i>查看详细资料</a>
                            </div>
                            <div className="edit_user">
                                <a href="#/user" onClick={(e) => { e.preventDefault(); setEditActive(true) }}>编辑个人资料</a>
                            </div>
                        </div>
                    </div>
                </div>
                {
                    editActive ? (<EditUser returnInfo={setEditActive} />) : (<div className="user_content_main">
                        <div className="user_content_trends">
                            <div className="user_content_trends_head">
                                <ul>
                                    <li className="active">
                                        <p onClick={(e) => { setCurrentContent("trends"); changeCurrentActive(e) }}>动态</p>
                                    </li>
                                    <li>
                                        <p onClick={(e) => { setCurrentContent("answer"); changeCurrentActive(e) }}>回答</p>
                                    </li>
                                    <li>
                                        <p onClick={(e) => { setCurrentContent("question"); changeCurrentActive(e) }}>提问</p>
                                    </li>
                                    <li>
                                        <p onClick={(e) => { changeCurrentActive(e) }}>评论</p>
                                    </li>
                                    <li>
                                        <p onClick={(e) => { changeCurrentActive(e) }}>更多</p>
                                    </li>
                                </ul>
                            </div>
                            <div className="user_content_trends_list">
                                {
                                    currentContent === "trends" && (
                                        attenQuestion.length === 0 ? (<div className="user_content_trends_list_none">
                                            <svg width="150" height="120" viewBox="0 0 150 120" fill="currentColor"><g fill="none" fillRule="evenodd"><path fill="#EBEEF5" d="M94 29v-2.002c0-.55.443-.998 1-.998h1c.553 0 1 .446 1 .998V29h2.002c.55 0 .998.443.998 1v1c0 .553-.446 1-.998 1H97v2.002c0 .55-.443.998-1 .998h-1c-.553 0-1-.446-1-.998V32h-2.002A.997.997 0 0 1 91 31v-1c0-.553.446-1 .998-1H94zm30.613 17.724l-21.82-4.638.207-3.023 22.237 4.727a6.004 6.004 0 0 1 4.62 7.122l-7.9 37.158a6.001 6.001 0 0 1-7.116 4.627l-15.31-3.254.63-2.934 15.31 3.25c1.62.34 3.218-.69 3.56-2.32l7.9-37.16a3.005 3.005 0 0 0-2.31-3.567zM48.596 85.727l.624 2.935-12.717 2.703a6.004 6.004 0 0 1-7.117-4.628L21.488 49.58a6.004 6.004 0 0 1 4.62-7.123L47 38.017l.133 3.038-20.402 4.337a3 3 0 0 0-2.3 3.564l7.9 37.157a3.005 3.005 0 0 0 3.56 2.317l12.71-2.703zM100 82c0 3.314-2.688 6-6.006 6H56.006A6.01 6.01 0 0 1 50 82V34c0-3.314 2.688-6 6.006-6h27.147v3H56.006A3.003 3.003 0 0 0 53 34v48c0 1.65 1.35 3 3.006 3h37.988A3.003 3.003 0 0 0 97 82V42.373h3V82zm-4.5-41C89.7 41 85 36.3 85 30.5S89.7 20 95.5 20 106 24.7 106 30.5 101.3 41 95.5 41zm0-3a7.5 7.5 0 1 0 0-15 7.5 7.5 0 0 0 0 15z" fillRule="nonzero"></path><path fill="#F7F8FA" d="M47 73.22l-6.484 1.378c-.82.174-1.333.97-1.16 1.78.173.816.97 1.327 1.784 1.154L47 76.287V73.22zm0-8.594l-4.58.974c-.8.17-1.324.968-1.152 1.778a1.494 1.494 0 0 0 1.775 1.156l3.957-.84v-3.068zm0-17.285a6.002 6.002 0 0 0-8 5.66 6.002 6.002 0 0 0 8 5.66V47.34zm56 29.88l6.178 1.318a1.5 1.5 0 1 0 .624-2.934L103 74.148v3.067zm0-8.58l4.275.91c.808.17 1.6-.34 1.775-1.157a1.507 1.507 0 0 0-1.15-1.78l-4.9-1.04v3.067zm0-8.97c.626.22 1.3.34 2 .34 3.314 0 6-2.685 6-6s-2.686-6-6-6c-.7 0-1.374.12-2 .34v11.32zM76 56a8 8 0 1 1 0-16 8 8 0 0 1 0 16zm-8 7.5c0-.828.667-1.5 1.505-1.5h12.99a1.5 1.5 0 1 1 0 3h-12.99A1.5 1.5 0 0 1 68 63.5zm-5 8c0-.828.67-1.5 1.49-1.5h23.02c.822 0 1.49.666 1.49 1.5 0 .828-.67 1.5-1.49 1.5H64.49c-.822 0-1.49-.666-1.49-1.5z"></path></g></svg>
                                            <p><span>刚来提问网?</span>试试去关注感兴趣的话题</p>
                                        </div>) : (
                                                attenQuestion.map(item => {
                                                    return (<QuestionCard key={item._id} question={item} me={false} />)
                                                })
                                            )
                                    )
                                }
                                {
                                    currentContent === "question" && (
                                        question.length === 0 ? (<p>还没有发布任何问题，赶紧去发布吧!</p>) : (
                                            question.map(item => {
                                                return (<QuestionCard key={item._id} question={item} me={true} />)
                                            })
                                        )
                                    )
                                }
                                {
                                    currentContent === "answer" && (
                                        likingAnswer.length === 0 ? (<p>还没点赞任何的回答，赶紧去查找你需要的问题看看吧!</p>) : (
                                            likingAnswer.map(item => {
                                                return (<AnswerCard key={item._id} answer={item} />)
                                            })
                                        )
                                    )
                                }
                            </div>
                        </div>
                        <div className="user_content_other">
                            <div className="user_content_other_like">
                                <ul>
                                    <li><p>我的粉丝</p><h5>{liker}</h5></li>
                                    <li><p>我的关注</p><h5>{user.following && user.following.length}</h5></li>
                                </ul>
                            </div>
                            <div className="user_content_other_atten">
                                <ul>
                                    <li>
                                        <p>关注的话题</p>
                                        <span>0</span>
                                    </li>
                                    <li>
                                        <p>关注的问题</p>
                                        <span>{attenQuestion.length}</span>
                                    </li>
                                    <li>
                                        <p>关注的评论</p>
                                        <span>0</span>
                                    </li>
                                </ul>
                            </div>
                            <div className="user_content_footer">
                                <p>&copy; CopyRight 2020/02/13 make chenGX</p>
                            </div>
                        </div>
                    </div>)
                }

            </div>
        </div>
    )
}

const mapStateToProps = (state) => {
    return {
        userInfo: state.home.userInfo
    }
}
const mapDispatchToProps = (dispatch) => {
    return {
        updateUserInfo(token) {
            const action = actionCreator.getUser(token)
            dispatch(action)
        }
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(User)